#include "atomic_0822_protocol_conversion_service.h"

// 辅助函数：获取当前毫秒级时间戳
static double getCurrentTimestampMs() {
    auto now = std::chrono::system_clock::now();
    auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
    return static_cast<double>(now_ms.time_since_epoch().count());
}

// 协议转换核心实现
int convertProtocol(ConversionInput *input, ConversionOutput *output) {
    // 入参合法性检查
    if (input == nullptr || output == nullptr) {
        return ATOMIC_SERVICE_ERROR;
    }

    // 初始化输出结构体基础字段
    output->device_id = input->device_id;
    output->timestamp = getCurrentTimestampMs();
    output->is_compressed = 0;  // 暂不实现压缩功能
    output->return_type = ATOMIC_SERVICE_SUCCESS;
    output->src_ip = "";            // 源IP默认空，由外部设置
    output->dest_ip = "";           // 目的IP默认空，由外部设置
    output->src_port = 0;           // 源端口默认0，由外部设置
    output->dest_port = 0;          // 目的端口默认0，由外部设置
    output->data_buffer[0] = '\0';  // 初始化缓冲区
    output->buffer_length = 0;

    // 根据协议类型进行转换
    switch (output->protocol_type) {
        case PROTOCOL_MQTT: {
            // MQTT协议格式：主题+负载（简化版）
            int ret = snprintf(output->data_buffer, sizeof(output->data_buffer),
                "MQTT Topic: /atomic/device/%d/signals\n"
                "Payload: {\"timestamp\":%.3f, \"vals\":[%.2f, %.2f, %.2f], "
                "\"valid_count\":%d, \"quality\":%d, \"filtered\":%s}",
                input->device_id,
                input->timestamp,
                input->processed_val1,
                input->processed_val2,
                input->processed_val3,
                input->valid_count,
                input->quality_score,
                input->is_filtered ? "true" : "false");

            if (ret < 0 || ret >= static_cast<int>(sizeof(output->data_buffer))) {
                output->return_type = ATOMIC_SERVICE_ERROR;
                return ATOMIC_SERVICE_ERROR;
            }
            output->buffer_length = ret;
            break;
        }

        case PROTOCOL_HTTP: {
            // HTTP协议格式：POST请求（简化版）
            std::stringstream http_stream;
            http_stream << "POST /device/data HTTP/1.1\r\n";
            http_stream << "Host: atomic-protocol-gateway\r\n";
            http_stream << "Content-Type: application/json\r\n";
            
            // 构建JSON请求体
            std::string json_body = "{"
                "\"device_id\":" + std::to_string(input->device_id) + ","
                "\"timestamp\":" + std::to_string(input->timestamp) + ","
                "\"processed_vals\":[" + 
                    std::to_string(input->processed_val1) + "," +
                    std::to_string(input->processed_val2) + "," +
                    std::to_string(input->processed_val3) + "],"
                "\"valid_count\":" + std::to_string(input->valid_count) + ","
                "\"quality_score\":" + std::to_string(input->quality_score) + ","
                "\"is_filtered\":" + (input->is_filtered ? "true" : "false") +
            "}";

            http_stream << "Content-Length: " << json_body.size() << "\r\n";
            http_stream << "\r\n";  // 头部结束标志
            http_stream << json_body;

            // 写入缓冲区
            std::string http_str = http_stream.str();
            if (http_str.size() >= sizeof(output->data_buffer)) {
                output->return_type = ATOMIC_SERVICE_ERROR;
                return ATOMIC_SERVICE_ERROR;
            }
            strncpy(output->data_buffer, http_str.c_str(), http_str.size() + 1);
            output->buffer_length = http_str.size();
            break;
        }

        case PROTOCOL_TCP_BIN: {
            // TCP二进制协议：固定格式二进制流（小端字节序）
            constexpr size_t BIN_BUFFER_SIZE = 4 + 8 + 8*3 + 4 + 4 + 1;  // 总长度：43字节
            if (BIN_BUFFER_SIZE > sizeof(output->data_buffer)) {
                output->return_type = ATOMIC_SERVICE_ERROR;
                return ATOMIC_SERVICE_ERROR;
            }

            char* buffer_ptr = output->data_buffer;
            size_t offset = 0;

            // 写入device_id（4字节int）
            *reinterpret_cast<int*>(buffer_ptr + offset) = input->device_id;
            offset += 4;

            // 写入timestamp（8字节double）
            *reinterpret_cast<double*>(buffer_ptr + offset) = input->timestamp;
            offset += 8;

            // 写入处理后的数据（3个double，各8字节）
            *reinterpret_cast<double*>(buffer_ptr + offset) = input->processed_val1;
            offset += 8;
            *reinterpret_cast<double*>(buffer_ptr + offset) = input->processed_val2;
            offset += 8;
            *reinterpret_cast<double*>(buffer_ptr + offset) = input->processed_val3;
            offset += 8;

            // 写入有效数据计数（4字节int）
            *reinterpret_cast<int*>(buffer_ptr + offset) = input->valid_count;
            offset += 4;

            // 写入质量评分（4字节int）
            *reinterpret_cast<int*>(buffer_ptr + offset) = input->quality_score;
            offset += 4;

            // 写入滤波标志（1字节bool）
            *reinterpret_cast<uint8_t*>(buffer_ptr + offset) = input->is_filtered ? 1 : 0;
            offset += 1;

            output->buffer_length = offset;
            break;
        }

        case PROTOCOL_JSON_RPC: {
            // JSON-RPC协议格式（2.0版本）
            int ret = snprintf(output->data_buffer, sizeof(output->data_buffer),
                "{"
                "\"jsonrpc\":\"2.0\","
                "\"method\":\"signal_data\","
                "\"params\":{"
                    "\"device_id\":%d,"
                    "\"timestamp\":%.3f,"
                    "\"processed_val1\":%.2f,"
                    "\"processed_val2\":%.2f,"
                    "\"processed_val3\":%.2f,"
                    "\"valid_count\":%d,"
                    "\"quality_score\":%d,"
                    "\"is_filtered\":%s"
                "},"
                "\"id\":1"
                "}",
                input->device_id,
                input->timestamp,
                input->processed_val1,
                input->processed_val2,
                input->processed_val3,
                input->valid_count,
                input->quality_score,
                input->is_filtered ? "true" : "false");

            if (ret < 0 || ret >= static_cast<int>(sizeof(output->data_buffer))) {
                output->return_type = ATOMIC_SERVICE_ERROR;
                return ATOMIC_SERVICE_ERROR;
            }
            output->buffer_length = ret;
            break;
        }

        case PROTOCOL_UNKNOWN:
        default:
            // 未知协议
            output->return_type = ATOMIC_SERVICE_NOT_SUPPORT;
            return ATOMIC_SERVICE_NOT_SUPPORT;
    }

    // 设置传输数据长度（与缓冲区有效长度一致）
    output->data_len = output->buffer_length;
    return output->return_type;
}